package stock;

import java.io.IOException;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 上海的数据抓取
 * 
 * @author houzhuo
 *
 */
public class Test4 {

	public static void main3(String[] args) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet post = new HttpGet(
				"http://yunhq.sse.com.cn:32041/v1/sh1/dayk/605589?callback=jQuery1124019642798431642916_1680766507262&begin=-1000&end=-1&period=day&_=1680766507265");
		HttpResponse response;
		try {
			response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			String data = EntityUtils.toString(entity);
			String content = data.substring(data.indexOf("(") + 1, data.length() - 1);
			JSONArray jsonarray = JSONObject.fromObject(content).getJSONArray("kline");
			for (int i = 0; i < jsonarray.size(); i++) {
				if (i == 0) {
					continue;
				}
				JSONArray jsonarray0 = JSONArray.fromObject(jsonarray.get(i - 1));// 昨天
				JSONArray jsonarray1 = JSONArray.fromObject(jsonarray.get(i));// 今天
				Float f = Float.valueOf(jsonarray1.getString(4));
				Float f1 = Float.valueOf(jsonarray0.getString(4));
				Float f2 = (f - f1) / f1 * 100;
				NumberFormat numberInstance = NumberFormat.getNumberInstance();
				numberInstance.setMaximumFractionDigits(2);
				numberInstance.setRoundingMode(RoundingMode.HALF_UP);
				String fs2 = numberInstance.format(f2);
				System.out.println("日期" + jsonarray1.getString(0) + "--当前价" + jsonarray1.getString(4) + "--成交量"
						+ jsonarray1.getString(5) + "--涨跌幅度:" + fs2);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

		System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
		@SuppressWarnings("resource")
		final WebClient webClient = new WebClient(BrowserVersion.CHROME);// 新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
		webClient.getOptions().setThrowExceptionOnScriptError(false);// 当JS执行出错的时候是否抛出异常, 这里选择不需要
		webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);// 当HTTP的状态非200时是否抛出异常, 这里选择不需要
		webClient.getOptions().setActiveXNative(false);
		webClient.getOptions().setCssEnabled(false);// 是否启用CSS, 因为不需要展现页面, 所以不需要启用
		webClient.getOptions().setJavaScriptEnabled(true); // 很重要，启用JS
		webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 很重要，设置支持AJAX
		webClient.getOptions().setThrowExceptionOnScriptError(false);
		webClient.setJavaScriptErrorListener(new MyJSErrorListener());
		HtmlPage page = null;
		try {
			page = webClient.getPage("http://www.sse.com.cn/market/price/report/");// 尝试加载上面图片例子给出的网页
		} catch (Exception e) {
			e.printStackTrace();
		}
		webClient.setJavaScriptTimeout(3000);
		webClient.waitForBackgroundJavaScript(3000);// 异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束

		try {
			Thread.sleep(4000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Iterable<DomNode> list1 = page.getByXPath("//tbody//tr");
		Iterable<DomNode> date = page.getByXPath("//span[@class='new_date']");
		if (date.iterator().hasNext()) {
			String str = date.iterator().next().asNormalizedText();
			str = str.replace("更新时间：", "").substring(0, 10);
			System.out.println(str);
		}
		System.out.println(date.iterator().next().asNormalizedText());
		HtmlElement div = null;
		HtmlElement button = null;
		saveCode(list1);
		try {
			for (int i = 0; i < 90; i++) {
				div = (HtmlElement) (page.getByXPath("//li[@class='next']").get(0));
				button = (HtmlElement) div.getFirstChild();
				button.click();
				page = null;
				page = button.click();
				webClient.waitForBackgroundJavaScript(3000);
				Thread.sleep(4000);
				Iterable<DomNode> list2 = page.getByXPath("//tbody//tr");
				saveCode(list2);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// save coode 上海的
	public static void saveCode(Iterable<DomNode> list1) {
		for (DomNode domNode : list1) {
			List<DomNode> listTD = domNode.getChildNodes();
			System.out.println(domNode.asNormalizedText());

		}
	}

}
